#include "src/dataview.h"
#include <qobject.h>
#ifdef _MSWIN_
#include <windows.h>
#include <winsock2.h>
#endif

// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "mainwidget.h"
#include "udps.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>

QT_USE_NAMESPACE

/*
 * /ssd2/data/test_re/hb-tick-202312-202401.bin
 * /ssd2/data/okex/signal/signal-202312-202401.json
 * 2444800 5348231 4081280 4570000
 */

/*
 * /ssd2/data/test_re/hb-tick-202312-202401.bin
 * /hdd1/dumper.bin 2444800 4576000 4081280
 * 4570000
 */

static pthread_t tid_udps = 0;

void
release_data()
{
  close_udp_server();
  pthread_join(tid_udps, nullptr);

  Trade::release_shared_memory(
    g_dp.mem_key, g_dp.tick, g_dp.tick_size, g_dp.vo_size);
}

int
main(int argc, char* argv[])
{
  if (argc != 3) {
    printf("Usage %s <memory key> <start pos>\n", argv[0]);
    return (0);
  }

  int ret = Trade::load_data_from_shared_memory(
    argv[1], &g_dp.tick, &g_dp.tick_size, &g_dp.vo, &g_dp.vo_size);
  if (ret)
    return (-2);

  g_dp.mem_key = argv[1];
  g_dp.m_posIndex = g_dp.g_start_idx = std::stoll(argv[2]);

  pthread_create(&tid_udps, nullptr, udp_main, nullptr);

  QApplication a(argc, argv);
  QApplication::connect(&a, &QApplication::aboutToQuit, &release_data);

  MainWidget w;

  QObject::connect(&sender,
                   &Sender::sig_received_position,
                   &w,
                   &MainWidget::received_position);
  QObject::connect(&sender,
                   &Sender::sig_set_pet_dir_time,
                   &w,
                   &MainWidget::received_pet_dir_time);
  QObject::connect(
    &sender, &Sender::sig_mickey_lines, &w, &MainWidget::received_mickey_lines);
  QObject::connect(&sender,
                   &Sender::sig_received_action,
                   w.getDataView(),
                   &DataView::rececived_action);
  QObject::connect(&sender,
                   &Sender::sig_clear_action,
                   w.getDataView(),
                   &DataView::clear_action);
  QObject::connect(&sender,
                   &Sender::sig_received_reverse_sapce,
                   &w,
                   &MainWidget::received_reverse_space);

  const int win_width = 1200;
  w.resize(win_width, 560);
  QSize size = qApp->screens()[0]->size();
  w.move((size.width() - win_width) / 2, 80);
  w.show();

  return a.exec();
}
